import time

from selenium import webdriver

from common.logger import hslogger
from dao.BaseRepository import BaseRepository

browser = webdriver.Chrome()
hsgame_dao = BaseRepository(collectionname="hsgame")


def main():
    # result, num, msg = hsgame_dao.get_all_no_page(sort=[("modifyTime", -1)])
    result, num, msg = hsgame_dao.get_all_no_page(sort=[("createTime", -1)])
    for r in result:
        print(r.get("name"))

    url = 'https://pan.baidu.com'

    # 声明浏览器
    browser.get(url)

    time.sleep(10)
    # browser.close()  # 关闭浏览器

    browser.find_element_by_xpath('//*[@id="TANGRAM__PSP_4__footerULoginBtn"]').click()
    browser.find_element_by_xpath('//*[@id="TANGRAM__PSP_4__userName"]').send_keys("terrydash")
    time.sleep(1)
    browser.find_element_by_xpath('//*[@id="TANGRAM__PSP_4__password"]').send_keys("52xuguoxu")
    browser.get_screenshot_as_file("a.png")
    browser.find_element_by_xpath('// *[ @ id = "TANGRAM__PSP_4__submit"]').click()

    r = ""
    while r.upper() != "Y":
        r = input("是否进入，Y OR N:")
    r = browser.find_element_by_xpath('//*[@id="dialog1"]/div[2]/div/div[2]')
    if r:
        r.click()

    for r in result:
        print(r.get("name"))
        if "downloadUrl" in r and len(str(r.get("downloadUrl"))) > 0 and str(r.get("downloadUrl")).startswith(
                "https://pan.baidu"):
            r["downloadUrl"] = str(r.get("downloadUrl")).replace("https://pan.baidu.chttps://pan.baidu.com/s",
                                                                 "https://pan.baidu.com/s")
            try:
                baidupan_save(r.get("downloadUrl"), r)
                time.sleep(1)
            except Exception as e:
                hslogger.error(e)
                continue


def baidupan_save(url, r):
    browser.get(url)

    try:
        if len(str(r.get("downloadPassword"))) > 0 and browser.find_element_by_class_name(
                "g-button-right") is not None and browser.find_element_by_class_name(
                "input-area") is not None and browser.find_element_by_class_name("input-area").find_element_by_tag_name(
                "input") is not None:
            browser.find_element_by_class_name("input-area").find_element_by_tag_name("input").send_keys(
                r.get("downloadPassword"))
            browser.find_element_by_class_name("g-button-right").click()
            time.sleep(10)

    finally:
        pass
    time.sleep(1)
    try:
        if len(browser.find_elements_by_xpath('//*[@id="share_nofound_des"]')) == 0:
            browser.find_element_by_xpath('//*[@id="shareqr"]/div[2]/div[2]/div/ul[1]/li[1]/div/span[1]').click()
            time.sleep(1)
            browser.find_element_by_xpath('//*[@id="bd-main"]/div/div[1]/div/div[2]/div/div/div[2]/a[1]').click()
            time.sleep(1)
            browser.find_element_by_class_name("g-button-blue-large").click()
            time.sleep(2)
    finally:
        pass


if __name__ == "__main__":
    main()
